﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Utils
{
    public class Util
    {/// <summary>
        /// 按照位数生成字母和数字的混合字符
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string RadomString(int length)
        {
            StringBuilder newRandom = new StringBuilder();
            Random rd = new Random();
            string str = @"0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ";
            for (var i = 0; i < length; i++)
            {
                if (i % 2 == 0)
                {
                    newRandom.Append(str[rd.Next(11, 62)].ToString().ToLower());
                }
                else
                {
                    newRandom.Append(str[rd.Next(0, 11)]);
                }
            }
            return newRandom.ToString();
        }
        /// <summary>
        ///  POST 数据到服务器
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="data">post参数</param>
        /// <returns></returns>
        public static string CreateHttpPostRequest(string url, string data)
        {
            string recievedata = "";
            try
            {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                byte[] byteArray = Encoding.UTF8.GetBytes(data);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse())
                {
                    if (webResponse.StatusCode == HttpStatusCode.OK)
                    {
                        // 获取接收到的流 
                        using (Stream stream = webResponse.GetResponseStream())
                        {
                            using (StreamReader sr = new StreamReader(stream))
                            {
                                recievedata = sr.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                recievedata = "发送短信错误：url:" + url + ";data=" + data + e.Message + e.StackTrace;
            }
            return recievedata;
        }

        /// <summary>
        /// 获取客户机的ＩＰ
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string ip = "";
            if (System.Web.HttpContext.Current != null)
            {
                System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
                System.Web.HttpServerUtility Server = System.Web.HttpContext.Current.Server;

                string addr = "";
                try
                {
                    /*穿过代理服务器取远程用户真实IP地址：*/
                    if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                    {
                        addr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                    }
                    else
                    {
                        addr = Request.ServerVariables["REMOTE_ADDR"].ToString();
                    }
                }
                catch
                {
                    addr = Request.UserHostAddress;
                }

                if (addr == null)
                {
                    addr = "";
                }

                ip = addr.Split(',')[0];
            }
            return ip;
        }

        /// <summary>
        /// 计算Ip地址的整数值
        /// </summary>
        /// <param name="strIp">Ip地址</param>
        /// <returns>返回类型为ulong的长整数值</returns>
        public static long ComputeIpValue(string strIp)
        {
            string[] ipVals = strIp.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            long rst = long.Parse(ipVals[3]);
            rst += long.Parse(ipVals[2]) * 256;
            rst += long.Parse(ipVals[1]) * 256 * 256;
            rst += long.Parse(ipVals[0]) * 256 * 256 * 256;
            return rst;
        }
    }
}
